package structure.array;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
* @description: 稀疏数组
* @author: wangjun
* @create: 2022-04-11
*/
public class SparseArrayMain {

    int[][] originArray;
    int[][] sparseArray;

    /**
     * 初始化二维数组
     * @param n 二维数组的大小
    */
    public void initOriginArray(int n){
        originArray = new int[n][n];
        originArray[1][2] = 1;
        originArray[2][3] = 2;
    }

    /**
     * 输出二维数组
     */
    public void printArray(int[][] array){
        for (int[] row : array){
            for (int data : row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
    }

    /**
     * 将原始二维数组转换成稀疏数组
     */
    public void sparseArray(int[][] originArray){
        int sum = 0;
        // 统计原始数组中有多个有效字符
        for (int[] row : originArray){
            for (int data : row){
                if(data != 0){
                    sum++;
                }
            }
        }
        sparseArray = new int[sum+1][3];
        sparseArray[0][0] = originArray.length;
        sparseArray[0][1] = originArray[0].length;
        sparseArray[0][2] = sum;
        int count = 0;
        for (int i = 0; i < originArray.length; i++) {
            for (int j = 0; j < originArray[i].length; j++) {
                if(originArray[i][j] != 0){
                    ++count;
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = originArray[i][j];
                }
            }
        }

        File file = new File("resource/sparse.txt");
        try (FileWriter writer = new FileWriter(file)) {
            for (int[] row : sparseArray){
                for (int data : row){
                    String value = String.valueOf(data);
                    writer.write(value + "\t");
                }
                writer.write("\r\n");
            }
        } catch (IOException e) {
            throw new RuntimeException("写入异常");
        }
    }

    public static void main(String[] args) {
        SparseArrayMain sparseArrayMain = new SparseArrayMain();
        sparseArrayMain.initOriginArray(11);
        System.out.println("原始数组：");
        sparseArrayMain.printArray(sparseArrayMain.originArray);
        System.out.println("稀疏数组：");
        sparseArrayMain.sparseArray(sparseArrayMain.originArray);
        sparseArrayMain.printArray(sparseArrayMain.sparseArray);
    }
}